<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <!-- 用户管理卡片 -->
    <el-card class="user-management-card">
      <!-- 搜索和操作区域 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="searchKeyWord" placeholder="请输入用户名称" clearable @input="queryUsers()">
              <template #append>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="departmentSelection" placeholder="选择部门" clearable @change="queryUsers()">
              <el-option label="全部部门" value=""></el-option>
              <el-option label="系统管理部" value="系统管理部"></el-option>
              <el-option label="质检部" value="质检部"></el-option>
              <el-option label="工艺部" value="工艺部"></el-option>
              <el-option label="质量管理部" value="质量管理部"></el-option>
              <el-option label="供应链部" value="供应链部"></el-option>
            </el-select>
          </el-col>
          <el-col :span="14">
            <div class="action-buttons">
              <el-button type="success" @click="addUserButton">新增用户</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 分隔线 -->
      <el-divider></el-divider>
      <!-- 用户表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="username" label="用户名称"></el-table-column>
        <el-table-column prop="name" label="用户姓名"></el-table-column>
        <el-table-column label="角色">
          <template #default="scope">
            {{ getRoleName(scope.row.roleId) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码"></el-table-column>
        <el-table-column prop="department" label="部门/单位"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="primary" @click="viewUser(scope.row)">查看</el-button>
            <el-button size="small" type="danger" @click="deleteUser()">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="table-footer">
        <div class="table-info">显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize,
          total) }}
          条，共 {{ total }} 条记录</div>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
          layout="sizes, prev, pager, next" :total="total" @current-change="handleCurrentPageChange"
          @size-change="handleSizeChange" />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="resetForm">
      <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="userForm.department" placeholder="请选择部门" @change="handleDepartmentChange">
            <el-option label="系统管理部" value="系统管理部"></el-option>
            <el-option label="质检部" value="质检部"></el-option>
            <el-option label="工艺部" value="工艺部"></el-option>
            <el-option label="质量管理部" value="质量管理部"></el-option>
            <el-option label="供应链部" value="供应链部"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色" :disabled="isEdit" @change="handleRoleChange">
            <el-option label="系统管理员" value="0"></el-option>
            <el-option label="质检员" value="1"></el-option>
            <el-option label="工艺工程师" value="2"></el-option>
            <el-option label="质量经理" value="3"></el-option>
            <el-option label="供应链主管" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>

        <!-- 密码字段 - 仅新增时显示 -->
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="footer-left">
            <el-button v-if="isEdit" type="warning" @click="resetUserPasswordBox(userForm.username)">重置密码</el-button>
          </div>
          <div class="footer-right">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 查看用户详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="查看用户详情" width="700px" class="user-detail-dialog">
      <div class="user-detail-content">

        <el-divider></el-divider>

        <el-descriptions :column="2" border class="user-descriptions">
          <el-descriptions-item label="用户名" label-class-name="detail-label">
            <span class="detail-value">{{ viewUserData.username }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="真实姓名" label-class-name="detail-label">
            <span class="detail-value">{{ viewUserData.name }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="密码" label-class-name="detail-label">
            <div class="password-field">
              <span class="detail-value password-text">
                {{ showPassword ? viewUserData.password || '骗你的看不了密码哈哈哈哈哈哈Ciallo～(∠・ω< )⌒☆' : '******' }} </span>
                  <el-button :icon="showPassword ? Hide : View" size="small" text @click="togglePassword"
                    class="password-toggle">
                    {{ showPassword ? '隐藏' : '显示' }}
                  </el-button>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="角色" label-class-name="detail-label">
            <el-tag type="primary" class="role-tag">{{ getRoleName(viewUserData.roleId) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="手机号码" label-class-name="detail-label">
            <span class="detail-value">{{ viewUserData.phone }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="部门/单位" label-class-name="detail-label">
            <span class="detail-value">{{ viewUserData.department }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2" label-class-name="detail-label">
            <span class="detail-value">{{ viewUserData.createTime }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="账号" label-class-name="detail-label">
            <span class="detail-value">{{ viewUserData.updateTime }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer-enhanced">
          <el-button @click="viewDialogVisible = false" size="large">关闭</el-button>
          <el-button type="primary" @click="editUserFromView" size="large">
            <el-icon>
              <Edit />
            </el-icon>
            编辑用户
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, User, View, Hide, Edit } from '@element-plus/icons-vue'
import { addUsersService, queryUsersService, updateUsersService, resetPasswordService } from '@/api/AdminApi'


const searchKeyWord = ref('')
const departmentSelection = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(8)

const tableData = ref([
  {
    userId: 1,
    username: '',
    name: '',
    roleId: '',
    phone: '',
    department: '',
    createTime: '',
    updateTime: ''
  }
])

const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const isEdit = ref(false)
const userFormRef = ref()

// 新增查看用户详情相关的响应式数据
const viewDialogVisible = ref(false)
const showPassword = ref(false)
const viewUserData = ref({
  username: '',
  name: '',
  roleId: '',
  phone: '',
  department: '',
  createTime: '',
  updateTime: '',
  password: '' // 添加密码字段
})

const userForm = reactive({
  userId: 0,
  username: '',
  name: '',
  roleId: '',
  phone: '',
  department: '',
  password: '',
  createTime: '',
  updateTime: ''
})


const userFormRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  phone: [{ required: false, message: '请输入手机号码', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const addUserButton = () => {
  resetForm()
  dialogTitle.value = '新增用户'
  isEdit.value = false
  dialogVisible.value = true
}

const addUser = async () => {
  let result = await addUsersService({
    ...userForm,
    roleId: Number(userForm.roleId) // 将roleId从string转换为number类型
  })
  ElMessage.success(result.data?.msg || '添加成功')
  // 刷新页面
  queryUsers()
  resetForm()
}

const editUser = (row: any) => {
  dialogTitle.value = '编辑用户'
  isEdit.value = true
  Object.assign(userForm, {
    ...row,
    roleId: String(row.roleId) // 确保roleId是字符串类型，以便在el-select中正确显示
  })
  dialogVisible.value = true
}

// 修改viewUser方法，显示用户详情弹窗
const viewUser = (row: any) => {
  Object.assign(viewUserData.value, row)
  // 模拟密码数据，实际项目中应该从后端获取
  //viewUserData.value.password = '123456'
  showPassword.value = false
  viewDialogVisible.value = true
}

// 切换密码显示/隐藏
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 从查看窗口跳转到编辑
const editUserFromView = () => {
  viewDialogVisible.value = false
  editUser(viewUserData.value)
}

// 根据roleID获取角色名称
const getRoleName = (roleId: string) => {
  const roleMap: { [key: string]: string } = {
    '0': '系统管理员',
    '1': '质检员',
    '2': '工艺工程师',
    '3': '质量经理',
    '4': '供应链主管'
  }
  return roleMap[roleId] || '未知角色'
}

// 处理部门变化，自动设置对应角色
const handleDepartmentChange = (department: string) => {
  // 部门和角色的映射关系
  const departmentRoleMap: { [key: string]: string } = {
    '系统管理部': '0', // 系统管理员
    '质检部': '1',     // 质检员
    '工艺部': '2',     // 工艺工程师
    '质量管理部': '3', // 质量经理
    '供应链部': '4'    // 供应链主管
  }
  // 无论新增还是编辑模式，选择部门都会自动设置对应角色
  userForm.roleId = departmentRoleMap[department] || '0'
}

// 处理角色变化，自动设置对应部门
const handleRoleChange = (roleId: string) => {
  // 角色和部门的映射关系
  const roleDepartmentMap: { [key: string]: string } = {
    '0': '系统管理部', // 系统管理员
    '1': '质检部',     // 质检员
    '2': '工艺部',     // 工艺工程师
    '3': '质量管理部', // 质量经理
    '4': '供应链部'    // 供应链主管
  }
  // 只有在新增模式下才自动设置部门
  // 编辑模式下角色字段是禁用的，不会触发此函数
  if (!isEdit.value) {
    userForm.department = roleDepartmentMap[roleId] || ''
  }
}

//重置表格
const resetForm = () => {
  Object.assign(userForm, {
    userId: null,
    username: '',
    name: '',
    roleId: '',
    phone: '',
    department: '',
    password: '',
  })
  userFormRef.value?.resetFields()
}

// 统一处理表单提交
const handleSubmit = () => {
  if (isEdit.value) {
    saveUser()
  } else {
    addUser()
  }
}

// 修改用户
const saveUser = async () => {
  let result = await updateUsersService({
    ...userForm,
    roleId: Number(userForm.roleId) // 将roleId从string转换为number类型
  })
  ElMessage.success(result.data?.msg || '修改成功')
  // 刷新页面
  queryUsers()
  // 关闭对话框
  dialogVisible.value = false
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  queryUsers()
}

const handleCurrentPageChange = (val: number) => {
  currentPage.value = val
  queryUsers()
}

const logout = () => {
  ElMessageBox.confirm('确定要退出系统吗？', '确认退出', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('退出成功')
  })
}

//分页查询员工
const queryUsers = async () => {
  let params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    username: searchKeyWord.value,
    department: departmentSelection.value
  }
  let result = await queryUsersService(params);
  //渲染页面
  tableData.value = result.data.records
  total.value = result.data.total
}

//删除员工
const deleteUser = async () => {
  ElMessage.error('删除不了的骗你哈哈哈哈哈（既然你看到了就由你来实现吧）Ciallo～(∠・ω< )⌒☆')
}

//重置员工密码弹窗
const resetUserPasswordBox = async (username: string) => {
  ElMessageBox.confirm(
    '确定重置该用户的密码吗？（默认密码为123456）',
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      //删除学生
      resetPasswordUser(username)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

const resetPasswordUser = async (username: string) => {
  let result = await resetPasswordService(username) as any
  ElMessage.success(result.msg || '重置成功')
}

onMounted(() => {
  queryUsers()
  console.log('用户管理页面加载完成')
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
  }

  &.el-button--primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    }
  }

  &.el-button--success {
    background: linear-gradient(135deg, #55863e 0%, #52c41a 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #5aa036 0%, #73d13d 100%);
    }
  }

  &.el-button--warning {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #e081e9 0%, #e3455a 100%);
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
    border: none;

    &:hover {
      background: linear-gradient(135deg, #ff888c 0%, #fdbedc 100%);
    }
  }
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: white;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-management-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);

  .table-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    padding: 16px 0;

    .table-info {
      color: #8492a6;
      font-size: 14px;
    }
  }
}

.search-section {
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.footer-left {
  display: flex;
  align-items: center;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 用户详情对话框样式 */
.user-detail-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.user-detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.user-avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
}

.user-avatar {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  font-size: 32px;
}

.user-basic-info h3 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.user-descriptions {
  margin-top: 20px;
}

.user-descriptions :deep(.el-descriptions__label) {
  background-color: #f8f9fa !important;
  font-weight: 600;
  color: #495057;
  width: 120px;
}

.user-descriptions :deep(.el-descriptions__content) {
  background-color: #ffffff;
  padding: 12px 16px;
}

.detail-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.password-field {
  display: flex;
  align-items: center;
  gap: 10px;
}

.password-text {
  font-family: 'Courier New', monospace;
  background: #f5f5f5;
  padding: 4px 8px;
  border-radius: 4px;
  min-width: 80px;
}

.password-toggle {
  color: #409eff;
  font-size: 12px;
}

.password-toggle:hover {
  background-color: #ecf5ff;
}

.role-tag {
  font-weight: 600;
  padding: 4px 12px;
}

.status-icon {
  margin-right: 4px;
}

.dialog-footer-enhanced {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0 10px 0;
}

.dialog-footer-enhanced .el-button {
  padding: 12px 24px;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-detail-dialog {
    width: 95% !important;
  }

  .user-avatar-section {
    flex-direction: column;
    text-align: center;
  }

  .user-descriptions :deep(.el-descriptions) {
    display: block;
  }

  .user-descriptions :deep(.el-descriptions__body .el-descriptions__table) {
    display: block;
  }

  .user-descriptions :deep(.el-descriptions__body .el-descriptions__table .el-descriptions__row) {
    display: block;
    margin-bottom: 10px;
  }
}

/* 滚动条美化 */
.user-detail-content::-webkit-scrollbar {
  width: 6px;
}

.user-detail-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.user-detail-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.user-detail-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;

}

/* 密码提示样式 */
.password-hint {
  margin-top: 5px;
}

.password-hint .el-text {
  font-size: 12px;
  color: #909399;
}

/* 密码输入框样式优化 */
.el-form-item .el-input--password {
  position: relative;
}

.el-form-item .el-input--password:hover {
  border-color: #409eff;
}

.el-form-item .el-input--password:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>